define(
    ['knockout', 'platform.common', 'bootbox', 'knockout-bsTable', 'knockout-jsTree', 'knockout-component', 'bootstrapValidator', 'bootstrapValidator-zhCN', 'sco.msg'],
    function (ko, platform, bootbox) {

        var rest = {
            get: function (codeId) {
                //暂未使用
                var param = {};
                param.code_id = codeId;
                var result = platform.servicebreak('~/rest/pubcode/selectOne', param).responseJSON;
                return result;
            },
            remove: function (codeId) {
                var param = {};
                param.code_id = codeId;
                platform.servicebreakAsync('~/rest/pubcode/delete', param,
                    'post', function () {
                        platform.showOperTip('DEALING');
                    }).done(function (response) {
                    if (response instanceof Object && response.meta.success) {
                        viewModel.tableViewModel.refresh();
                        viewModel.refreshTree();
                    }
                });
            },
            save: function (param) {
                platform.servicebreakAsync('~/rest/pubcode/save', param,
                    'post', function () {
                        platform.showOperTip('DEALING');
                    }).done(function (response) {
                    if (response instanceof Object && response.meta.success) {
                        platform.showOperTip('SAVESUC');
                        viewModel.tableViewModel.refresh();
                        viewModel.refreshTree();

                        // 是否继续添加
                        // bootbox.confirm({
                        //     title: '继续新增提示',
                        //     size: 'small',
                        //     message: '是否继续新增该节点下数据?',
                        //     buttons: {
                        //         confirm: {
                        //             label: '继续',
                        //             className: 'btn-success btn-sm'
                        //         },
                        //         cancel: {
                        //             label: '取消',
                        //             className: 'btn-default btn-sm'
                        //         }
                        //     },
                        //     callback: function (result) {
                        //         if (result) {
                        //             viewModel.codeViewModel.resetForm();
                        //             var pid = null;
                        //             viewModel.codeViewModel.showNewForm(pid);
                        //         } else {
                        //             viewModel.codeViewModel.close();
                        //         }
                        //     }
                        // });
                    }
                });
            },
            loadTreeNodes: function () {
                return platform.servicebreak('~/rest/pubcode/getTreeNodes', {
                    nodeId: ''
                }).responseJSON;
            }
        };

        var kbTable = require('knockout-bsTable');
        var jsTree = require('knockout-jsTree');

        var ViewModel = function () {
            var self = this;
            self.selectedNode = ko.observable();
            self.treeViewModel = new jsTree.jsTreeViewModel({
                core: {
                    data: {
                        url: platform.mapUrl('~/rest/pubcode/getTreeNodes?lazy'),
                        data: function (node) {
                            return JSON.stringify({'nodeId': node.id});
                        },
                        contentType: 'application/json',
                        dataType: 'json',
                        method: 'post'
                    }
                },
                plugins: ['wholerow']
            });
            self.onTreeNodeSelected = function (event, data) {
                var param = {};
                if (data.node.parent == '#') {
                    param.p_code_id = '';
                    self.selectedNode('');
                } else {
                    param.p_code_id = data.node.id;
                    self.selectedNode(data.node.id);
                }
                self.tableViewModel.refresh(param);
            };
            self.columns = [
                {
                    checkbox: true, align: 'center', width: 30
                },
                {
                    field: 'display_order',
                    title: '序号',
                    formatter: function (value, row, index) {
                        var options = self.tableViewModel.getOptions();
                        var indexPageNum = parseInt(options.pageNumber);
                        var indexPageSize = parseInt(options.pageSize);
                        return ((indexPageNum - 1) * indexPageSize)
                            + (index + 1);
                    },
                    width: 35,
                    align: 'center'
                }, {
                    field: 'code_id', title: 'PK', visible: false
                }, {
                    field: 'code_value', title: '码值'
                }, {
                    field: 'code_text', title: '中文释义'
                }, {
                    field: 'p_code_id', title: 'Pid', visible: false
                }];
            self.tableViewModel = new kbTable.bootstrapTableViewModel({
                url: platform.mapUrl('~/rest/pubcode/list'),
                toolbar: '#toolbar',
                queryParams: function (params) {
                    return {
                        pageNumber: params.offset / params.limit + 1,
                        pageSize: params.limit,
                        p_code_id: ''
                    };
                },
                columns: self.columns
            });
            self.refreshTree = function () {
                var data = rest.loadTreeNodes();
                self.treeViewModel.refresh(data);
            };
            self.modalVisible = ko.observable(false);
            self.codeViewModel = {//变量驼峰命名，传入后台使用_命名
                title: ko.observable(),
                enabled: ko.observable(),//是否启用
                codeId: ko.observable(),//主键ID
                codeValue: ko.observable(),//码值
                codeText: ko.observable(),//中文释义
                pCodeId: ko.observable(),//父级主键ID
                editStatus: ko.observable('0'),//可编辑状态 0 新增 1 修改
                resetForm: function () {
                    $('#detailForm').resetForm();//表单重置

                    if ($('#detailForm').data('bootstrapValidator') != null ||
                        $('#detailForm').data('bootstrapValidator') != undefined) {
                        $('#detailForm').data('bootstrapValidator').resetForm();
                    }

                    //ko绑定重置
                    this.enabled();
                    this.codeId('');
                    this.codeValue('');
                    this.codeText('');
                    this.pCodeId('');
                    this.editStatus('');
                    this.enabled(true);
                },
                disableForm: function () {
                    $('#detailForm').find('input,textarea').attr('disabled', true);
                },
                enableForm: function () {
                    $('#detailForm').find('input,textarea').attr('disabled', false);
                },
                setFormData: function (codeId) {
                    var result = rest.get(codeId);
                    if (result instanceof Object && result.meta.success) {
                        var info = result.responseObject;
                        this.codeId(info.code_id);
                        this.codeValue(info.code_value);
                        this.codeText(info.code_text);
                        this.pCodeId(info.p_code_id);
                    }
                },
                validateForm: function () {
                    $('#detailForm').bootstrapValidator({
                        message: 'This value is not valid',
                        feedbackIcons: {
                            valid: 'glyphicon glyphicon-ok',
                            invalid: 'glyphicon glyphicon-remove',
                            validating: 'glyphicon glyphicon-refresh'
                        },
                        excluded: [':disabled'],
                        fields: {
                            codeValue: {
                                validators: {
                                    notEmpty: {
                                        message: '码值为必填字段,不可为空'
                                    }
                                }
                            },
                            codeText: {
                                validators: {
                                    notEmpty: {
                                        message: '中文释义为必填字段,不可为空'
                                    }
                                }
                            }
                        }
                    });
                },
                showNewForm: function (pid) {
                    this.resetForm();
                    this.validateForm();
                    this.enableForm();

                    this.title('新增公共代码');
                    this.codeId(platform.uuid());
                    this.editStatus('0');

                    if (pid != undefined && pid != null) {
                        this.pCodeId(pid);
                    }
                    self.modalVisible(true);
                },
                showEditForm: function (codeId) {
                    this.resetForm();
                    this.validateForm();
                    this.enableForm();

                    this.title('编辑公共代码');
                    this.setFormData(codeId);
                    self.modalVisible(true);
                },
                showViewForm: function (codeId) {//if necessary
                    this.resetForm();
                    this.disableForm();

                    this.title('查看公共代码');
                    this.setFormData(codeId);
                    this.enabled(false);
                    self.modalVisible(true);
                },
                save: function () {
                    $('#detailForm').data('bootstrapValidator').validate();
                    if (!$('#detailForm').data('bootstrapValidator').isValid()) {
                        platform.showOperTip('VALIDATEFAIL');
                        return;
                    }

                    var param = {};
                    param.code_id = this.codeId();
                    param.code_value = this.codeValue();
                    param.code_text = this.codeText();
                    param.edit_status = this.editStatus();
                    if (param.edit_status == '0') {
                        param.p_code_id = this.pCodeId();
                    }
                    rest.save(param);
                },
                close: function () {
                    self.modalVisible(false);
                    $('#codeDialog').toggleClass('hide');
                }
            };
            self.fnAdd = function () {
                var node = self.selectedNode();
                if (node == undefined) {
                    bootbox.confirm({
                        title: '系统提示',
                        size: 'small',
                        message: '确认是否新增公共代码分组?',
                        buttons: {
                            confirm: {
                                label: '确认',
                                className: 'btn-success btn-sm'
                            },
                            cancel: {
                                label: '取消',
                                className: 'btn-default btn-sm'
                            }
                        },
                        callback: function (result) {
                            if (result) {
                                self.codeViewModel.showNewForm();
                                $('#codeDialog').toggleClass('hide');
                            }
                        }
                    });
                } else {
                    self.codeViewModel.showNewForm(node);
                    $('#codeDialog').toggleClass('hide');
                }
            };
            self.fnRemove = function () {
                var selections = self.tableViewModel.getSelections();
                if (selections.length = 1) {
                    bootbox.confirm({
                        title: '删除提示',
                        size: 'small',
                        message: '是否删除该节点数据?',
                        buttons: {
                            confirm: {
                                label: '确认',
                                className: 'btn-success btn-sm'
                            },
                            cancel: {
                                label: '取消',
                                className: 'btn-default btn-sm'
                            }
                        },
                        callback: function (result) {
                            if (result) {
                                rest.remove(selections[0].code_id);
                            }
                        }
                    });
                } else {
                    platform.showTip('REMOVE');
                }
            }
        };

        var viewModel = new ViewModel();
        return viewModel;
    });